package pool

import (
	"fmt"
	redisConn "github.com/go-redis/redis"
	poolConstruct "github.com/silenceper/pool"
	"github.com/spf13/viper"
	"shortURL/pkg/redis"
)

func initRedisPool() error {
	Cache = make(map[string]poolConstruct.Pool)

	for _, name := range viper.GetStringSlice("pool.initial_cache_pool") {
		poolConfig := &poolConstruct.Config{
			InitialCap: viper.GetInt(fmt.Sprintf("redis.%s.initialCap", name)), //资源池初始连接数
			MaxIdle:    viper.GetInt(fmt.Sprintf("redis.%s.maxIdle", name)),    //最大空闲连接数
			MaxCap:     viper.GetInt(fmt.Sprintf("redis.%s.maxCap", name)),     //最大并发连接数
			Factory: func() (interface{}, error) {
				return redis.GetRedisInstance(redis.RedisOption{
					Address:  viper.GetString(fmt.Sprintf("redis.%s.host", name)),
					Password: viper.GetString(fmt.Sprintf("redis.%s.password", name)),
					Db:       viper.GetInt(fmt.Sprintf("redis.%s.database", name)),
				}), nil
			},
			Close: func(v interface{}) error {
				return v.(*redisConn.Client).Close()
			},
			Ping: func(v interface{}) error {
				_, err := v.(*redisConn.Client).Ping().Result()
				return err
			},
			//连接最大空闲时间，超过该时间的连接 将会关闭，可避免空闲时连接EOF，自动失效的问题
			IdleTimeout: viper.GetDuration(fmt.Sprintf("redis.%s.idleTimeout", name)),
		}

		p, err := poolConstruct.NewChannelPool(poolConfig)
		if err != nil {
			return err
		}

		Cache[name] = p
	}

	return nil
}
